using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SoundManager : MonoBehaviour
{
    private AudioSource m_MusicAudio;
    private AudioSource m_SoundAudio;
    private float SoundVolume
    {
        get { return PlayerPrefs.GetFloat("SoundVolume", 1); }
        set 
        {
            m_SoundAudio.volume = value;
            PlayerPrefs.SetFloat("SoundVolume", value); 
        }
    }
    private float MusicVolume
    {
        get { return PlayerPrefs.GetFloat("MusicVolume", 1); }
        set
        {
            m_MusicAudio.volume = value;
            PlayerPrefs.SetFloat("MusicVolume", value);
        }
    }

    private void Awake()
    {
        m_MusicAudio = this.gameObject.AddComponent<AudioSource>();
        m_MusicAudio.playOnAwake = false;
        m_MusicAudio.loop = true;

        m_SoundAudio = this.gameObject.AddComponent<AudioSource>();
        //m_SoundAudio.playOnAwake = false;
        m_SoundAudio.loop = false;
    }

    public void PlayMusic(string name)
    {
        //音量过小不播放
        if (this.MusicVolume < 0.1f)
            return;
        //如果当前音乐与要播放的音乐相同，则不播放
        string oldName = "";
        if(m_MusicAudio.clip != null)
            oldName = m_MusicAudio.clip.name;
        string trueName = name.Substring(0, name.IndexOf("."));
        if (oldName == trueName)
        {
            m_MusicAudio.Play();
            return;
        }
        
        Manager.Resource.LoadMusic(name,
            (Object obj) =>
            {
                m_MusicAudio.clip = obj as AudioClip;
                m_MusicAudio.Play();
            }
            );
    }

    public void PauseMusic()
    {
        m_MusicAudio.Pause();
    }
    public void OnUnPauseMusic()
    {
        m_MusicAudio.UnPause();
    }    
    public void StopMusic()
    {
        m_MusicAudio.Stop();
    }

    public void PlaySound(string name)
    {
        if (this.SoundVolume < 0.1f)
        {
            return;
        }

        //没有这段代码会导致重复加载，在加载ab包时报错。为什么解决方式为加载bundle包的时候创建字典，而不是在这个方法中解决

        //string oldName = "";
        //if (m_SoundAudio.clip != null)
        //    oldName = m_SoundAudio.clip.name;
        //string trueName = name.Substring(0, name.IndexOf("."));
        //if (oldName == trueName)
        //{
        //    m_SoundAudio.Play();
        //    return;
        //}

        Manager.Resource.LoadSound(name,
            (Object obj) =>
            {
                m_SoundAudio.PlayOneShot(obj as AudioClip);
            }
            );
    }

    public void SetMusicVolume(float volume)
    {
        this.MusicVolume = volume;
    }
    public void SetSoundVolume(float volume)
    {
        this.SoundVolume = volume;
    }

    void Start()
    {
        
    }

    void Update()
    {
        
    }
}
